package com.jack.helloworld.liveWallpaper;

import android.app.Activity;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.jack.helloworld.R;
import com.jack.helloworld.util.Constants;
import com.jack.helloworld.util.SharedPreferenceHelper;

import java.io.File;
import java.io.IOException;

public class VideoLoaderActivity extends Activity implements View.OnClickListener {

    private SurfaceView mVideoLoaderSurfaceView;
    private Button mVideoLoaderSetWallpaperButton;
    private MediaPlayer mMediaPlayer;

    private boolean mHasVoice;
    private int mPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_loader);

        initView();
        initEvent();
    }

    @Override
    protected void onStart() {
        super.onStart();
        String path = getIntent().getStringExtra(Constants.SP_LIVE_WALLPAPER_KEY_URI);
        initData(path);
    }

    private void initData(String path) {

        mHasVoice = (Boolean) SharedPreferenceHelper.read(VideoLoaderActivity.this,
                Constants.SP_LIVE_WALLPAPER,
                Constants.SP_LIVE_WALLPAPER_KEY_VOICE,
                SharedPreferenceHelper.BOOLEAN_VALUE);

        mMediaPlayer = new MediaPlayer();

        //设置播放时打开屏幕
        mVideoLoaderSurfaceView.getHolder().setKeepScreenOn(true);
        mVideoLoaderSurfaceView.getHolder().addCallback(new MySurfaceView(path));
    }

    private void initEvent() {
        mVideoLoaderSetWallpaperButton.setOnClickListener(this);

    }

    private void initView() {
        mVideoLoaderSurfaceView = (SurfaceView) findViewById(R.id.sf_video_loader);
        mVideoLoaderSetWallpaperButton = (Button) findViewById(R.id.btn_video_loader_set_wallpaper);

    }



    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_video_loader_set_wallpaper:
                setLiveWallPaper();
                break;

            default:
                break;
        }

    }


    private void setLiveWallPaper() {

        VideoLiveWallpaperService.VideoEngine engine = VideoLiveWallpaperService.engine;

        if (engine != null && engine.getMediaPlayer() != null) {
            secondSetLiveWallPaper(engine);
            sendExitBroadcast();
            finish();
        } else {
            firstSetLiveWallPaper();
        }

    }

    private void sendExitBroadcast() {
        Intent intent = new Intent(Constants.EXIT_ACTION);
        sendBroadcast(intent);
    }

    private void secondSetLiveWallPaper(VideoLiveWallpaperService.VideoEngine engine) {
        engine.initVideoLiveWallpaper(engine.getSurfaceHolder());
    }

    private void firstSetLiveWallPaper() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 16) {
            /*
             * Open live wallpaper preview (API Level 16 or greater).
             */
            intent.setAction(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
            intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(this, VideoLiveWallpaperService.class));
        } else {
            /*
             * Open live wallpaper picker (API Level 15 or lower).
             *
             * Display a quick little message (toast) with instructions.
             */
            intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
            Resources res = getResources();
            String hint = res.getString(R.string.picker_toast);
            Toast toast = Toast.makeText(this, hint, Toast.LENGTH_LONG);
            toast.show();
        }

        startActivityForResult(intent, Constants.LIVE_WALLPAPER_REQUEST_CODE);
    }

    public void play(String path) throws IllegalArgumentException, SecurityException,
            IllegalStateException, IOException {
        mMediaPlayer.reset();

        File file = new File(path);
        if (file.exists() && file.isFile()) {
            mMediaPlayer.setDataSource(path);
        } else {
            AssetManager assetMg = getApplicationContext().getAssets();
            AssetFileDescriptor fileDescriptor = assetMg.openFd("girl.mp4");
            mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(), fileDescriptor.getLength());
        }

        if (mHasVoice) {
            mMediaPlayer.setVolume(1.0f, 1.0f);
        } else {
            mMediaPlayer.setVolume(0, 0);
        }

        // 把视频输出到SurfaceView上
        mMediaPlayer.setDisplay(mVideoLoaderSurfaceView.getHolder());
        // 通过异步的方式装载媒体资源
        mMediaPlayer.prepareAsync();
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                // 装载完毕回调
                mMediaPlayer.start();
            }
        });
    }

    private class MySurfaceView implements SurfaceHolder.Callback {

        String path;

        public MySurfaceView(String path) {
            this.path = path;
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            if (mPosition == 0) {
                try {
                    play(path);
                    mMediaPlayer.seekTo(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
        }

    }

    @Override
    protected void onPause() {
        // 保存当前播放的位置
        mPosition = mMediaPlayer.getCurrentPosition();
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMediaPlayer.seekTo(mPosition);
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
        mMediaPlayer.release();
        mMediaPlayer = null;
        super.onDestroy();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.LIVE_WALLPAPER_REQUEST_CODE) {
            sendExitBroadcast();
            finish();
        }
    }
}
